package com.boomshake.controller;

import com.boomshake.common.PageResult;
import com.boomshake.common.Result;
import com.boomshake.dto.SetDistributorDTO;
import com.boomshake.dto.UserPageQueryDTO;
import com.boomshake.service.UserService;
import com.boomshake.utils.JwtUtil;
import com.boomshake.vo.SetDistributorVO;
import com.boomshake.vo.UserPageVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * 管理端用户管理Controller
 *
 * @author BoomShake
 * @date 2024-12-16
 */
@Slf4j
@RestController
@RequestMapping("/admin/user")
@CrossOrigin(origins = {"http://localhost:5173", "http://localhost:5174", "http://127.0.0.1:5173", "http://127.0.0.1:5174"}, allowCredentials = "true", maxAge = 3600)
public class AdminUserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 分页查询用户列表
     */
    @GetMapping("/list")
    public Result<PageResult<UserPageVO>> getUserList(UserPageQueryDTO queryDTO, HttpServletRequest request) {
        try {
            // 获取当前管理员ID
            getCurrentAdminId(request);
            
            PageResult<UserPageVO> pageResult = userService.getUserList(queryDTO);
            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("查询用户列表失败", e);
            return Result.error("查询用户列表失败：" + e.getMessage());
        }
    }

    /**
     * 查询用户详情
     */
    @GetMapping("/{userId}")
    public Result<UserPageVO> getUserDetail(@PathVariable Long userId, HttpServletRequest request) {
        try {
            // 获取当前管理员ID
            getCurrentAdminId(request);
            
            UserPageVO userDetail = userService.getUserDetail(userId);
            return Result.success(userDetail);
        } catch (Exception e) {
            log.error("查询用户详情失败", e);
            return Result.error("查询用户详情失败：" + e.getMessage());
        }
    }

    /**
     * 设置分销员
     */
    @PostMapping("/{userId}/set-distributor")
    public Result<SetDistributorVO> setDistributor(@PathVariable Long userId, 
                                                 @Valid @RequestBody SetDistributorDTO dto,
                                                 HttpServletRequest request) {
        try {
            // 获取当前管理员ID
            Long adminId = getCurrentAdminId(request);
            
            SetDistributorVO result = userService.setDistributor(userId, dto, adminId);
            return Result.success("分销员设置成功", result);
        } catch (Exception e) {
            log.error("设置分销员失败", e);
            return Result.error("设置分销员失败：" + e.getMessage());
        }
    }

    /**
     * 从请求中获取当前管理员ID
     */
    private Long getCurrentAdminId(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        String token = jwtUtil.getTokenFromHeader(authHeader);
        
        if (token == null || !jwtUtil.validateToken(token)) {
            throw new RuntimeException("token无效或已过期，请重新登录");
        }
        
        return jwtUtil.getUserIdFromToken(token);
    }
} 